//
//  STDSRenderTarget.hpp
//  STDRenderSDK
//
//  Created by 陈学明 on 2023/3/12.
//

#ifndef STDSRenderTarget_hpp
#define STDSRenderTarget_hpp

#include <stdio.h>
#include "STDSOpenGL.h"
#include "STDSTexture.hpp"

using namespace std;
class STDSRenderTarget {
public:
    STDSRenderTarget() {

    }

    STDSRenderTarget(int _w, int _h, bool _dep = false) {
        create(_w, _h, _dep);
    }

    ~STDSRenderTarget() {
//        printf("dealloc--STDSRenderTarget\n");
        _release();
    }

    void setBgColor(float r, float g, float b, float a) {
        bgR = r;
        bgG = g;
        bgB = b;
        bgA = a;
    }

    void create(int _w, int _h, bool _dep = false);

    void createFromTexture(shared_ptr<STDSTexture> _tex, bool _dep = false);

    void bindSelf(bool _clear = false);

    void restore();

    void resize(int _w, int _h, bool _dep);

    void resize(int _w, int _h);

    GLuint getTexId(){
        if(!mTexture)
            return 0;
        return mTexture->getId();
    }

    shared_ptr<STDSTexture> getTexture(){
        return mTexture;
    }

    int getWidth(){
        return mSizeW;
    }

    int getHeight(){
        return mSizeH;
    }

    bool isUseDepth() {
        return mbWithDep;
    }

    int getMemSize() {
        return mSizeMEM;
    }

    int *getPreViewport() {
        return mPreViewport;
    }

    int getPreFboId() {
        return mPreFboId;
    }

    int getPreDepId() {
        return mPreDepId;
    }

    bool isSize(int _w, int _h) {
        return mSizeW == _w && mSizeH == _h;
    }

    void calcMemSize() {
        int sizeTEX{0};
        int sizeDEP{0};
        sizeTEX = 4 * mSizeW * mSizeH / 1024;   // 32位
        if(mbWithDep)
            sizeDEP = 2 * mSizeW * mSizeH / 1024;   // 16位
        mSizeMEM = sizeTEX + sizeDEP;
    }

    void setPreInfo(STDSRenderTarget *_rt) {
        memcpy(mPreViewport, _rt->getPreViewport(), sizeof(int) * 4);
        mPreFboId = _rt->getPreFboId();
        mPreDepId = _rt->getPreDepId();
    }

private:
    void _release();

private:
    GLuint mFboId{HANDLE_NON};
    shared_ptr<STDSTexture> mTexture{nullptr};
    int mSizeW{0};
    int mSizeH{0};
    int mPreViewport[4] = {0};
    int mPreFboId{0};
    int mPreDepId{0};
    bool mbActivated{false};        // 当前 STDSRenderTarget 是否处于活跃(使用)状态
    bool mbWithDep{false};          // 是否包含深度信息
    bool mbTexExt{false};           // 是否来自外部纹理

    static float bgR;
    static float bgB;
    static float bgG;
    static float bgA;

    int mSizeMEM{0};
};
#endif /* STDSRenderTarget_hpp */
